<template>
    <div class="messageView">

        <div v-for="texts in editorText">
            <EditorComponent class="editor" v-model="texts.text" :documentModel="modelValue" placeholder="请输入内容..." titlePlaceholder="请输入标题..." />
        </div>
        <div class="aiResponse" v-if="aiResponse.length > 0" v-html="renderCustomHTML()"></div>
        
        <button @click="toggleMode(false)">富文本框模式</button>
        <button @click="toggleMode(true)">文档编辑模式</button>
        <button @click="consoleEditText">输出文本</button>
        <button @click="sendMessage">发送消息</button>
    </div>
</template>

<script lang="ts">
import EditorComponent from '@/components/EditorComponent.vue'; 
import { nextTick, ref } from 'vue';
import { OllamaApi } from '@/api/Ollama';

export default {
    name: 'messageView',
}
</script>

<script setup lang="ts">
    const editorTitle = ref();
    const editorText = ref([
        { text: '', title: '' },
        { text: '', title: '' },
        { text: '', title: '' },
        { text: '', title: '' },
        { text: '', title: '' },

    ]);
    const modelValue = ref(true);
    const aiResponse = ref("");
    // 切换模式
    const toggleMode = (value: boolean) => {
        modelValue.value = value;
    }

    const editorComponent = ref();

    const test = () => {
        
        let ref = document.querySelector('.editor');
        for (let i = 0; i < 10; i++) {
            ref = ref.querySelector('.editor');
        }
    }


    // 输出编辑内容
    const consoleEditText = () => {
        // console.log(editorComponent.value.getEditorText());
        console.log(editorText.value);
    }
    // 发送消息给AI
    const sendMessage = () => {
        console.log(editorTitle.value);
        let editorTitleValue = "";
        // 发送消息给AI
        OllamaApi.sendGeneralMessage({message: editorTitle.value, sessionId: ''}, async (chunk) => {
            editorTitleValue += chunk.message;
            aiResponse.value = editorTitleValue;
            await nextTick(); // 等待 Vue 更新 DOM
        }).then(response => {
            aiResponse.value = response.message;
            console.log(aiResponse.value);
        });
    }

    const renderCustomHTML = () => {
        const parser = new DOMParser();
        const doc = parser.parseFromString(aiResponse.value, 'text/html');
        // 在这里可以特殊处理 <think> 标签
        return doc.body.innerHTML;
    }
</script>

<style scoped>
.messageView {
    width: 100%;
    height: 100%;
    z-index: 0;
    position: relative;
}
.editor {
    width: 100%;
    height: calc(100% - 42px);
}

button {
    margin-right: 20px;
}

.aiResponse {
    position: absolute;
    width: 80%;
    height: calc(90% - 120px);
    top: calc(5% + 120px);
    left: 10%;
    /* 开启横向滚动条 */
    overflow-x: auto;
    background-color: aqua;
}

:deep(think) {
  display: block;
  color: red;
}
</style>